<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;

/**
 * 私悦接口
 */
class Pleasure extends Api
{
    protected $noNeedLogin = ['getPleasureInfoLike','getPleasureRemark','getPleasureSearch','getPleasureHot'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 私悦列表
     * @param string $type  查询类型：1=点赞排序,2=随机排序
     * @param string $search_name  搜索内容
     * @param string $page  页码，默认为1
     * @param string $page_size  每页数量，默认15
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="私悦视频id")
     * @ApiReturnParams   (name="name", type="string", required=true, sample="返回成功",description="私悦视频名")
     * @ApiReturnParams   (name="try_file", type="string", required=true, sample="返回成功",description="私悦视频试看地址")
     * @ApiReturnParams   (name="formal_file", type="string", required=true, sample="返回成功",description="私悦视频正式地址")
     * @ApiReturnParams   (name="like_num", type="string", required=true, sample="返回成功",description="点赞数量")
     * @ApiReturnParams   (name="remark_num", type="string", required=true, sample="返回成功",description="评论数量")
     * @ApiReturnParams   (name="is_like", type="string", required=true, sample="返回成功",description="是否点赞：1=已点赞，2=未点赞")
     * @ApiReturnParams   (name="formal_file", type="string", required=true, sample="返回成功",description="私悦视频正式地址")
     * @ApiReturnParams   (name="formal_file", type="string", required=true, sample="返回成功",description="私悦视频正式地址")
     * @ApiReturnParams   (name="formal_file", type="string", required=true, sample="返回成功",description="私悦视频正式地址")
     */
    public function getPleasureInfoLike()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
        }else{
            $lang_type = 1;
        }
        $page = input("page")?input("page"):1;
        $page_size = input("page_size")?input("page_size"):15;
        $where = "lang_type = ".$lang_type;

        $search_name = input("search_name");
        if($search_name){
            $episode_character = DB::name("episode_character")->where("name like '%".$search_name."%'")->select();
            if($episode_character){
                foreach($episode_character as $key => $val){
                    $search_arr[] = $val['id'];
                }
                $search_str = implode(",",$search_arr);
                $where .= " and episode_character_id in (".$search_str.")";
                $where .= " or name like '%".$search_name."%'";
            }else{
                $where .= " and name like '%".$search_name."%'";
            }

            //插入搜索记录
            $search_data = array(
                "user_id" => $this->auth->id,
                "search_value" => $search_name,
                "lang_type" => $lang_type,
                "create_time" => date("Y-m-d H:i:s")
            );
            DB::name("pleasure_search")->insert($search_data);
        }

        $type = input("type")?input("type"):2;
        if($type == 1){
            $sort = "like_num desc";
            $list = DB::name("pleasure_info")->where($where)->order($sort)->page($page,$page_size)->select();
        }else{
            $sort = "rand() desc";
            $list = DB::name("pleasure_info")->where($where)->orderRaw($sort)->page($page,$page_size)->select();
        }
        $source = input("source");

        foreach($list as $key => $val){
            if($this->auth->id){
                $pleasure_like = DB::name("pleasure_like")->where("user_id =".$this->auth->id." and pleasure_info_id =".$val['id']." and pleasure_remark_id = 0")->find();
                if($pleasure_like){
                    $list[$key]['is_like'] = 1;
                }else{
                    $list[$key]['is_like'] = 2;
                }
            }else{
                $list[$key]['is_like'] = 2;
            }
            
            if($source == 1){
                if($val['media_id']){
                    $access_token = $this->get_access_token();
                    $url = 'https://api.weixin.qq.com/wxa/sec/vod/getmedialink?access_token='.$access_token;
                    $data = array(
                        "media_id" => $val['media_id'],
                        "t" => time()+3600
                    );
                    //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
                    $res = json_decode($this->json_post($url,$data),true);
                    if($res['errcode'] == '0'){
                        $media_info = $res['media_info'];
                        $list[$key]['formal_file'] = $media_info['mp4_url'];
                    }
                    
                    $try_data = array(
                        "media_id" => $val['try_media_id'],
                        "t" => time()+3600
                    );
                    //这里要把传递的参数给转成json，不然小程序接口会报数据类型错误。
                    $res = json_decode($this->json_post($url,$try_data),true);
                    if($res['errcode'] == '0'){
                        $media_info = $res['media_info'];
                        $list[$key]['try_file'] = $media_info['mp4_url'];
                    }
                }
            }
        }
        $result['list'] = $list;
        $result['total'] = DB::name("pleasure_info")->where($where)->count();
        $this->success('查询成功', $result);
    }

    /**
     * 私悦点赞/取消点赞
     * @ApiMethod (POST)
     * @param string $pleasure_info_id  私悦视频id
     * @param string $pleasure_remark_id  私悦评论id
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function doLikePleasure()
    {
        $pleasure_info_id = input("pleasure_info_id");
        if(empty($pleasure_info_id)){
            $this->error("请选择点赞视频");
        }
        
        $where = array(
            "pleasure_info_id" => $pleasure_info_id
        );
        $pleasure_remark_id = input("pleasure_remark_id");
        if($pleasure_remark_id){
            $where['pleasure_remark_id'] = $pleasure_remark_id;
        }

        $pleasure_info = DB::name("pleasure_info")->where("id",$pleasure_info_id)->find();
        if(empty($pleasure_info)){
            $this->error("该私悦视频有误");
        }

        $pleasure_like = DB::name("pleasure_like")->where($where)->find();
        if($pleasure_like){
            DB::name("pleasure_like")->where("id",$pleasure_like['id'])->delete();
            if(empty($pleasure_remark_id)){
                if(DB::name("pleasure_info")->where("id",$pleasure_info_id)->value('like_num') > 0){
                    DB::name("pleasure_info")->where("id",$pleasure_info_id)->setDec("like_num");
                }
            }else{
                if(DB::name("pleasure_remark")->where("id",$pleasure_remark_id)->value('like_num') > 0){
                    DB::name("pleasure_remark")->where("id",$pleasure_remark_id)->setDec("like_num");
                }
            }
            $msg = "取消点赞成功";
        }else{
            $data = array(
                "user_id" => $this->auth->id,
                "pleasure_info_id" => $pleasure_info_id,
                "pleasure_remark_id" => $pleasure_remark_id,
                "lang_type" => $pleasure_info['lang_type'],
                "create_time" => date("Y-m-d H:i:s")
            );
            DB::name("pleasure_like")->insert($data);
            if(empty($pleasure_remark_id)){
                DB::name("pleasure_info")->where("id",$pleasure_info_id)->setInc("like_num");
            }else{
                DB::name("pleasure_remark")->where("id",$pleasure_remark_id)->setInc("like_num");
            }
            $msg = "点赞成功";
        }
        $this->success($msg);
    }

    
    /**
     * 私悦评论
     * @ApiMethod (POST)
     * @param string $pleasure_info_id  私悦视频id
     * @param string $pleasure_remark_id  私悦评论id
     * @param string $remark  评论内容
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     */
    public function doRemarkPleasure()
    {
        $pleasure_info_id = input("pleasure_info_id");
        if(empty($pleasure_info_id)){
            $this->error("请选择评论视频");
        }
        $remark = input("remark");
        if(empty($remark)){
            $this->error("评论内容不能为空");
        }

        $logic = new \app\api\filterWords();
        $remark = $logic->filter($remark,3);
        if (strpos($remark, "*") !== false) {
            $this->error("评论失败，评论内容含有违禁词");
        }
        
        $where = array(
            "pleasure_info_id" => $pleasure_info_id
        );
        $pleasure_info = DB::name("pleasure_info")->where("id",$pleasure_info_id)->find();
        if(empty($pleasure_info)){
            $this->error("该私悦视频有误");
        }

        $pleasure_remark_id = input("pleasure_remark_id");
        if($pleasure_remark_id){
            $pleasure_remark = DB::name("pleasure_remark")->where("id",$pleasure_remark_id)->find();
            if(empty($pleasure_remark)){
                $this->error("该评论不存在");
            }
            $where['pleasure_remark_id'] = $pleasure_remark_id;
            $remark_user_id = $pleasure_remark['user_id'];
        }else{
            $remark_user_id = 0;
        }

        $data = array(
            "user_id" => $this->auth->id,
            "pleasure_info_id" => $pleasure_info_id,
            "pleasure_remark_id" => $pleasure_remark_id,
            "remark_user_id" => $remark_user_id,
            "remark" => $remark,
            "lang_type" => $pleasure_info['lang_type'],
            "create_time" => date("Y-m-d H:i:s")
        );
        DB::name("pleasure_remark")->insert($data);
        if(empty($pleasure_remark_id)){
            DB::name("pleasure_info")->where("id",$pleasure_info_id)->setInc("remark_num");
        }
        $msg = "评论成功";
        $this->success($msg);
    }

    /**
     * 私悦评论列表
     * @param string $pleasure_info_id  私悦视频id
     * @param string $pleasure_remark_id  被评评论id
     * @param string $page  页码，默认为1
     * @param string $page_size  每页数量，默认15
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="评论id")
     * @ApiReturnParams   (name="user_id", type="string", required=true, sample="返回成功",description="评论人id")
     * @ApiReturnParams   (name="remark_user_id", type="string", required=true, sample="返回成功",description="被评人id")
     * @ApiReturnParams   (name="remark", type="string", required=true, sample="返回成功",description="评论内容")
     * @ApiReturnParams   (name="like_num", type="string", required=true, sample="返回成功",description="点赞数量")
     * @ApiReturnParams   (name="is_like", type="string", required=true, sample="返回成功",description="是否点赞：1=已点赞，2=未点赞")
     * @ApiReturnParams   (name="user_nickname", type="string", required=true, sample="返回成功",description="评论人姓名")
     * @ApiReturnParams   (name="user_avatar", type="string", required=true, sample="返回成功",description="被评人头像")
     * @ApiReturnParams   (name="pleasure_nickname", type="string", required=true, sample="返回成功",description="被评人名称，为空则不显示“回复”")
     * @ApiReturnParams   (name="pleasure_avatar", type="string", required=true, sample="返回成功",description="被评人头像")
     */
    public function getPleasureRemark()
    {
        $pleasure_info_id = input("pleasure_info_id");
        $pleasure_remark_id = input("pleasure_remark_id");
        $page = input("page")?input("page"):1;
        $page_size = input("page_size")?input("page_size"):15;
        if(empty($pleasure_info_id)){
            $this->error("请选择私悦视频");
        }
        
        $pleasure_info = DB::name("pleasure_info")->where("id",$pleasure_info_id)->find();
        if(empty($pleasure_info)){
            $this->error("该私悦视频不存在");
        }
        $where = array(
            "pleasure_info_id" => $pleasure_info_id,
            "pleasure_remark_id" => 0
        );

        if($pleasure_remark_id){
            $pleasure_remark = DB::name("pleasure_remark")->where("id",$pleasure_remark_id)->find();
            if(empty($pleasure_remark)){
                $this->error("该评论不存在");
            }
            $where["pleasure_remark_id"] = $pleasure_remark_id;
        }

        $list = DB::name("pleasure_remark")->where($where)->order("id desc")->page($page,$page_size)->select();
        foreach($list as $key => $val){
            if($this->auth->id){
                $pleasure_like = DB::name("pleasure_like")->where("user_id =".$this->auth->id." and pleasure_info_id =".$val['pleasure_info_id']." and pleasure_remark_id = ".$val['id'])->find();
                if($pleasure_like){
                    $list[$key]['is_like'] = 1;
                }else{
                    $list[$key]['is_like'] = 2;
                }
            }else{
                $list[$key]['is_like'] = 2;
            }

            $user = DB::name("user")->where("id",$val['user_id'])->field("nickname,avatar")->find();
            $list[$key]['user_nickname'] = $user['nickname'];
            $list[$key]['user_avatar'] = $user['avatar'];

            if($val['remark_user_id']){

                $pid_pleasure = DB::name("pleasure_remark")->where("id",$val['pleasure_remark_id'])->find();
                if($pid_pleasure['pleasure_remark_id']){
                    $pleasure_user = DB::name("user")->where("id",$val['remark_user_id'])->field("nickname,avatar")->find();
                    $list[$key]['pleasure_nickname'] = $pleasure_user['nickname'];
                    $list[$key]['pleasure_avatar'] = $pleasure_user['avatar'];
                }else{
                    $list[$key]['pleasure_nickname'] = '';
                    $list[$key]['pleasure_avatar'] = '';
                } 
                
            }else{
                $list[$key]['pleasure_nickname'] = '';
                $list[$key]['pleasure_avatar'] = '';
            }

            //增加一个二级评论回复总数
            $list[$key]['second_replay_num'] = DB::name("pleasure_remark")->where("pleasure_remark_id",$val['id'])->count();

        }
        $result['list'] = $list;
        $result['total'] = DB::name("pleasure_remark")->where($where)->count();
        $this->success('查询成功', $result);
    }


    /**
     * 猜你想搜
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="id")
     * @ApiReturnParams   (name="title", type="string", required=true, sample="返回成功",description="标题")
     */
    public function getPleasureHot()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
        }else{
            $lang_type = 1;
        }
        $where = array(
            "lang_type" => $lang_type
        );
        $result = DB::name("pleasure_hot")->where($where)->order("weigh desc")->limit(8)->select();
        $this->success('查询成功', $result);
    }

    /**
     * 历史搜索
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0",description="通讯状态，0为失败，1为成功")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功",description="返回内容")
     * @ApiReturnParams   (name="data",description="扩展数据返回")
     * @ApiReturnParams   (name="id", type="string", required=true, sample="返回成功",description="id")
     * @ApiReturnParams   (name="search_value", type="string", required=true, sample="返回成功",description="搜索内容")
     */
    public function getPleasureSearch()
    {
        if($this->auth->id){
            $user = DB::name("user")->where("id",$this->auth->id)->find();
            $lang_type = $user['lang_type'];
            $where = array(
                "lang_type" => $lang_type,
                "user_id" => $this->auth->id
            );
        }else{
            $lang_type = 1;
            $where = array(
                "lang_type" => $lang_type,
                "user_id" => 0
            );
        }
        $result = DB::name("pleasure_search")->where($where)->order("id desc")->select();
        $this->success('查询成功', $result);
    }

}